package com.example.logindemo.config;

import com.example.logindemo.entity.User;
import com.example.logindemo.entity.RunOrder;
import com.example.logindemo.repository.UserRepository;
import com.example.logindemo.repository.RunOrderRepository;
import com.example.logindemo.event.UserRegistrationEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.Random;

/**
 * 用户注册监听器
 * 当新用户注册时，自动为其创建测试跑单数据
 */
@Component
public class UserRegistrationListener implements ApplicationListener<UserRegistrationEvent> {

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private RunOrderRepository runOrderRepository;

    @Override
    public void onApplicationEvent(UserRegistrationEvent event) {
        User newUser = event.getUser();
        System.out.println("检测到用户注册事件：用户 " + newUser.getUsername() + " 注册成功");
        
        try {
            // 延迟执行，等待应用完全启动
            Thread.sleep(2000);
            // 为新用户创建测试跑单数据
            int ordersCreated = createTestRunOrdersForUser(newUser);
            System.out.println("为新用户 " + newUser.getUsername() + " 创建了 " + ordersCreated + " 个测试跑单");
        } catch (Exception e) {
            System.err.println("为新用户创建测试跑单失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 为指定用户创建测试跑单数据
     */
    private int createTestRunOrdersForUser(User user) {
        // 检查用户是否已有跑单数据
        long existingUserOrders = runOrderRepository.countByUserId(user.getId());
        if (existingUserOrders > 0) {
            System.out.println("用户 " + user.getUsername() + " 已存在 " + existingUserOrders + " 个跑单，跳过初始化");
            return 0;
        }

        Random random = new Random();
        String[] addresses = {
            "北京市朝阳区建国门外大街1号",
            "上海市浦东新区陆家嘴环路1000号", 
            "广州市天河区珠江新城花城大道85号",
            "深圳市南山区深南大道9988号",
            "杭州市西湖区文三路478号",
            "南京市鼓楼区中山北路32号",
            "成都市高新区天府大道1388号",
            "武汉市江汉区建设大道568号"
        };
        
        String[] statuses = {"pending", "in_progress", "completed", "cancelled"};
        String[] reviewStatuses = {"unreviewed", "reviewed", "good", "excellent"};

        // 为每个用户创建2-4个测试跑单
        int orderCount = 2 + random.nextInt(3); // 2-4个订单
        
        for (int i = 0; i < orderCount; i++) {
            RunOrder runOrder = new RunOrder();
            
            // 生成跑单ID
            String timestamp = String.valueOf(System.currentTimeMillis() + i * 1000 + user.getId() * 10000);
            String runOrderId = "R" + timestamp.substring(4) + String.format("%02d", user.getId());
            
            runOrder.setRunOrderId(runOrderId);
            runOrder.setOrderId("ORDER" + timestamp.substring(4, 12));
            runOrder.setUserId(user.getId());
            runOrder.setUserName(user.getUsername());
            runOrder.setDeliveryAddress(addresses[random.nextInt(addresses.length)]);
            runOrder.setStatus(statuses[random.nextInt(statuses.length)]);
            runOrder.setReviewStatus(reviewStatuses[random.nextInt(reviewStatuses.length)]);
            
            // 随机设置完成时间
            if ("completed".equals(runOrder.getStatus())) {
                Date completionTime = new Date(System.currentTimeMillis() - random.nextInt(Math.max(1, 7 * 24 * 60 * 60 * 1000)));
                runOrder.setCompletionTime(completionTime);
            }
            
            // 随机设置配送员
            if (!"pending".equals(runOrder.getStatus())) {
                runOrder.setDeliveryPerson("配送员" + (random.nextInt(9000) + 1000));
            }
            
            runOrder.setCreateTime(new Date(System.currentTimeMillis() - random.nextInt(Math.max(1, 30 * 24 * 60 * 60 * 1000))));
            runOrder.setUpdateTime(new Date());
            
            runOrderRepository.save(runOrder);
        }
        
        System.out.println("为用户 " + user.getUsername() + " 创建了 " + orderCount + " 个测试跑单");
        return orderCount;
    }
}